package homework.handler.stake;

import com.sun.net.httpserver.HttpExchange;
import homework.HttpUtils;
import homework.RequestMethod;
import homework.Resource;
import homework.handler.AbstractRequestHandler;
import homework.manager.SessionManager;
import homework.manager.StakeManager;

import java.io.IOException;
import java.util.Map;

@RequestMethod("POST")
public class StakeHandler extends AbstractRequestHandler<StakeRequest> {
    @Resource
    private SessionManager sessionManager;
    @Resource
    private StakeManager stakeManager;

    @Override
    public StakeRequest parse(HttpExchange exchange, String[] paths) {
        boolean match = paths.length > 2 && paths[2].equals("stake");
        if(match) {
            StakeRequest stakeRequest = new StakeRequest();
            Map<String, String> queryMap = HttpUtils.getQueryParams(exchange.getRequestURI().getQuery());
            String stake = HttpUtils.readRequestBody(exchange);
            stakeRequest.setOfferId(paths[1]);
            stakeRequest.setSessionKey(queryMap.get("sessionkey"));
            stakeRequest.setStake(stake);
            return stakeRequest;
        }
        return null;
    }

    @Override
    public void handle(HttpExchange exchange, StakeRequest request) throws IOException {
        if (sessionManager.isValidSession(request.getSessionKey())) {
            stakeManager.addStake(request.getOfferId(),
                    sessionManager.getCustomerId(request.getSessionKey()),
                    Integer.parseInt(request.getStake()));
            response(exchange, "");
        } else {
            error(exchange, "Invalid session key");
        }
    }
}
